<template>
  <div id="app">
    <input type="file" @change="handleFileChange">
    <el-button @click="handleUpload">上传</el-button>
  </div>
</template>

<script>
  import request from './utils/request';

  const SIZE = 1024 * 1024 * 2;
  export default {
    data() {
      return {
        container: {
          file: null//文件
        },
        data: []
      }
    },

    methods: {
      handleFileChange(e) {
        const [file] = e.target.files;
        window.console.log(file);
        if (file) {
          this.container.file = file;//
        }
      },
      //分片
      createFileChunk(file,size=SIZE) { //
        const fileChunkList = [];//[{file:},{file:},{}]
        let cur = 0;//cur+=size
        while (cur < file.size) {//Blog.prototype.slice
          fileChunkList.push({file: file.slice(cur, cur + size)})
          cur += size;
        }
        return fileChunkList;
      },

      //上传
      async uploadChunks() {
        //this.data [{chunk:切片文件,hash:文件的名字},{}]
        let requestList = this.data.map(({chunk, hash}) => {
          //创建formData
          const formData = new FormData();
          formData.append("chunk", chunk);
          formData.append("hash", hash);
          formData.append("filename", this.container.file.name);
          return {formData}

        }).map(async ({formData}) => request({
          url: "http://localhost:3000",
          data: formData
        }));
        //并发上传
        await Promise.all(requestList);
        // window.console.log(requestList);

      },

      //上传
      async handleUpload() {
        window.console.log(this.container.file);
        if (!this.container.file) return;

        //创建一个formData:向后端传递数据 前后端涉及到文件的操作
        let formData = new FormData();
        //{key:value}
        formData.append('filename', this.container.file);

        // 分片
        // 1:分片大小
        // 2:分片 slice
        // 3:并发 一同请求

        const fileChunkList = this.createFileChunk(this.container.file);
        //[{file:分片的文件}]==>[{chunk:file,hash:this.container.file.name}]
        // window.console.log(fileChunkList);

        this.data = fileChunkList.map(({file}, index) => ({
          chunk: file,
          hash: this.container.file.name + '-' + index
        }));

        // window.console.log(this.data);
        //{chunk:file,hash:传递到后台文件的名字}
        // 上传切片

        this.uploadChunks();


        // //请求
        // await request({//promise
        //   url: 'http://localhost:3000',//proxy
        //   data: formData
        // });
        // window.console.log(res);
      }
    }

  }
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
</style>
